package com.fand.site.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.fand.common.service.CommonService;

import com.fand.site.dto.DomainNaDto;

/**
 * 域名
 * 
 * @author yaoHT
 */
@Component(DomainNaValidator.BEAN_ID)
public class DomainNaValidator implements Validator {
	public static final String BEAN_ID = "com.fand.site.validator.DomainNaValidator";
	
	/**
	 * 公共服务
	 */
	@Qualifier(CommonService.BEAN_ID)
	@Autowired(required = false)
	private CommonService commonService;
	
	@Override
	public boolean supports(Class<?> clazz) {
		return DomainNaDto.class.equals(clazz);
	}
	
	@Override
	public void validate(Object target, Errors errors) {
		DomainNaDto domainNa = (DomainNaDto) target;
		
		if (StringUtils.isBlank(domainNa.getCode())) {
			errors.reject("code_required", "编号不能为空");
		} else {
			final int count = this.commonService.getSiteService().selectDomainNaByIdAndCodeForObject(
			        domainNa.getId(), domainNa.getCode());
			
			if (count > 0) {
				errors.reject("code_not_repeat", "编号不能重复");
			}
		}
	}
}
